package cn.itcast.goods.order.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.sun.org.apache.bcel.internal.generic.NEW;

import cn.itcast.bookstore.constants.PageConstants;
import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.book.domain.Book;
import cn.itcast.goods.order.domain.Order;
import cn.itcast.goods.order.domain.OrderItem;
import cn.itcast.goods.pager.PageBean;
import cn.itcast.jdbc.TxQueryRunner;

public class OrderDao {

	private QueryRunner qr= new TxQueryRunner();
	/**
	 * 创建订单
	 * @param order
	 * @throws SQLException 
	 */
	public void add(Order order) throws SQLException {
		// TODO Auto-generated method stub
		
		//1.添加订单
		String sql = "insert into t_order values (?,?,?,?,?,?) ";
		order.getOrderItemList();
		Object[] params = { order.getOid(),
				order.getOrdertime(),
				order.getTotal(),
				order.getStatus(),
				order.getAddress(),
				order.getOwner().getUid()
		};
	    qr.update(sql, params);
	    //2.添加订单条目
	    /*  准备批处理参数
		 *   一条insert语句需要一个Object[]为参数，那么多条insert就是Object[][]为参数。
		 */
	    Object[][] orderItemParams = new Object[order.getOrderItemList().size()][];
	    for(int i=0;i<order.getOrderItemList().size();i++){
	    	OrderItem item = order.getOrderItemList().get(i);
	    	orderItemParams[i] = new Object[]{item.getOrderItemId(),
	    			item.getQuantity(),item.getSubtotal(),item.getBook().getBid(),
	    			item.getBook().getBname(),item.getBook().getCurrPrice(),item.getBook().getImage_b(),item.getOrder().getOid()
	    	};	
	    }
	    sql =  "insert into t_orderitem values (?,?,?,?,?,?,?,?)";
	   qr.batch(sql, orderItemParams); 
	    
	       
	}
	/**
	 * 根据用户查询订单
	 * @param uid
	 * @param pc
	 * @return
	 * @throws SQLException 
	 */
	public PageBean<Order> findByUser(String uid, int pc) throws SQLException {
		// TODO Auto-generated method stub
		Map<String,Object> criteria = new HashMap<String, Object>();
		criteria.put("uid", uid);
		return findByCriteria(criteria,pc);
		
	}
	/**
	 * 根据条件查询订单
	 * @param criteria
	 * @param pc
	 * @return
	 * @throws SQLException 
	 */
	private PageBean<Order> findByCriteria(Map<String, Object> criteria, int pc) throws SQLException {
		// TODO Auto-generated method stub
		//1.创建sql子句
		List<Object> param = new ArrayList<Object>();
		StringBuilder wheresql =new StringBuilder("where 1=1");
		for(String name:criteria.keySet())
		{
		     Object value = criteria.get(name);
		     if(value == null){
		    	 continue;
		     }
		     wheresql.append(" and ").append(name).append("=?");
		     param.add(value);
		}
		//2.创建排序和Limit子句
		String orderByAndLimitSql = "order by ordertime limit ? offset ?";
		//3.生成个数查询语句，执行sql，得到记录数
		String cntSql = "select count(*) from t_order "+wheresql;
		Number cnt =(Number) qr.query(cntSql, new ScalarHandler(), param.toArray());
		int tr = cnt != null ? cnt.intValue(): 0;
	
		//4.生成记录查询，执行sql语句，得到当前记录页
		String sql = "select * from t_order " + wheresql + orderByAndLimitSql;
		 //计算Limit
		  int ps = PageConstants.ORDER_PAGE_SIZE;//得到每页记录数
		  param.add(ps);
		  param.add(ps*(pc-1)); //忽略几条记录
		  
		 //把MapList映射成List<Order>
		  List<Order> orderList = qr.query(sql, new BeanListHandler<Order>(Order.class), param.toArray());
		  for(Order order:orderList){
			  loadOrderItemList(order); //为当前的order加载其所有的orderitem
		  }
		//5.创建PageBean，返回
		  PageBean<Order> pb = new PageBean<Order>();
		  pb.setPc(pc);
		  pb.setPs(ps);
		  pb.setTr(tr);
		  pb.setDataList(orderList);
		return pb;
	}
	/**
	 * 当前order对象加载其所有的OrderItem
	 * @param order
	 * @throws SQLException 
	 */
	private void loadOrderItemList(Order order) throws SQLException {
		// TODO Auto-generated method stub
		//1.执行sql语句，得到map对象
		String sql = "select * from t_orderitem where oid = ?";
		List<Map<String,Object>> mapList= qr.query(sql, new MapListHandler(), order.getOid());
		//2.把map对象映射成orderItem 和book对象
		List<OrderItem> orderItemList = new ArrayList<OrderItem>();
		for(Map map:mapList)
		{
		
			OrderItem orderItem = CommonUtils.toBean(map, OrderItem.class);
			Book book = CommonUtils.toBean(map, Book.class);
			orderItem.setBook(book);
			orderItem.setOrder(order);
			
			orderItemList.add(orderItem);
		}
		
		//3.把得到的orderItem对象设置给order
		
		order.setOrderItemList(orderItemList);
	}
	
	/**
	 * 加载订单信息
	 * @param oid
	 * @return
	 * @throws SQLException 
	 */
	public Order load(String oid) throws SQLException {
		// TODO Auto-generated method stub
		String sql= "select * from t_order where oid =?";
		Order order =qr.query(sql, new BeanHandler<Order>(Order.class), oid);
		loadOrderItemList(order);
		return order;
	}
	
	/**
	 * 更新订单状态
	 * @param oid
	 * @param i
	 * @return
	 * @throws SQLException 
	 */
	public void updateStatus(String oid, int status) throws SQLException {
		// TODO Auto-generated method stub
		String  sql = "update t_order set status=? where oid = ?";
		qr.update(sql, status , oid);
	}
	
	/**
	 * 查找订单的状态
	 * @param oid
	 * @throws SQLException 
	 */
	public int findStatusByOrder(String oid) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "select status form t_order where oid = ?";
		Number number = (Number) qr.query(sql, new ScalarHandler(), oid);
		return number == null ? -1 : number.intValue() ;
		
	}

}